import time
from django.urls import reverse
from django.db.models import Q
from django.shortcuts import render,redirect
from django.http import StreamingHttpResponse,Http404
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
from music.models import *
from music.forms import CommentForm 
# Create your views here.




def music(request):
	#热搜歌曲,通过搜索得次数结合歌曲表联合，进行降序查询，并取前8个数据
	search_song = Dynamic.objects.select_related('song').order_by('-dynamic_search').all()[:8]
	#音乐分类，查询分类表得所有数据
	label_list = Label.objects.all()
	#热门歌曲：歌曲表和歌曲动态结合，查询播放次数进行降序排列显示
	play_hot_song = Dynamic.objects.select_related('song').order_by('-dynamic_plays').all()[:10]
	#新歌推荐
	daily_recommendation = Song.objects.order_by('song_release').all()[:3]
	#热门搜索，热门下载：
	search_ranking = search_song[:6]
	down_ranking = Dynamic.objects.select_related('song').order_by('-dynamic_down').all()[:6]

	all_ranking = [search_ranking,down_ranking]
	# import pandas as pd

	# # 将查询结果转换为 DataFrame
	# search_ranking_df = pd.DataFrame(list(search_song[:6].values()))
	# down_ranking_df = pd.DataFrame(list(Dynamic.objects.select_related('song').order_by('-dynamic_down').all()[:6].values()))

	# # 合并 DataFrame
	# combined_df = pd.concat([search_ranking_df, down_ranking_df]).drop_duplicates()

	# # 将处理后的结果转换回您需要的格式
	# all_ranking = list(combined_df.to_dict('records'))


	# print(all_ranking)



	return render(request, 'music_index.html',locals())



#歌曲排行榜详情页面
def rank(request):
	#热搜歌曲
	search_song = Dynamic.objects.select_related('song').order_by('-dynamic_search').all()[:4]
	#歌曲分类列表
	all_list = Song.objects.values('song_type').distinct()
	#歌曲列表信息
	song_type = request.GET.get('type','')
	if song_type:
		song_info = Dynamic.objects.select_related('song').filter(song__song_type=song_type).order_by('-dynamic_plays').all()[:10]
	else:
		song_info = Dynamic.objects.select_related('song').order_by('-dynamic_plays').all()[:10]

	return render(request,'rank.html',locals())



#歌曲播放
def play(request,song_id):
	#热搜歌曲
	search_song = Dynamic.objects.select_related('song').order_by('-dynamic_search').all()[:6]

	print(f'热搜歌曲1:{search_song}')
	#歌曲信息
	song_info = Song.objects.get(song_id=int(song_id))
	print(f'歌曲信息2:{song_info}')
	#播放列表
	play_list = request.session.get('play_list',[])
	
	song_exist = False
	
	if play_list:
		for i in play_list:
			if int(song_id)==i['song_id']:
				song_exist = True
	if song_exist == False:
		play_list.append({'song_id':int(song_id),'song_singer':song_info.song_singer,'song_name':song_info.song_name,'song_time':song_info.song_time})
		request.session['play_list'] = play_list

	import os
	basedir = os.path.dirname(os.path.abspath(__file__))
	file_path = os.path.join(basedir,'static/song_lyrics/test.txt')
	# print("绝对路径：", file_path)
	
	# file_path = 'static/song_lyrics/'+ song_info.song_lyrics
	# print("尝试读取的文件路径：", file_path)	

	# print(f'播放列表3:{play_list}')
	# #歌词
	if song_info.song_lyrics:
			f = open(file_path,'r',encoding='utf8')
			song_lyrics = f.read()
			f.close()



	# print(f'歌词4:{song_info.song_lyrics}')	
	
	#相关歌曲
	# song_type = Song.objects.values('song_type').get(song_id=song_id)
	song = Song.objects.get(song_id=song_id)
	song_type = song.song_type

	# current_song_type = song_type  # 获取当前歌曲的类型

	# # 然后根据这个类型获取相同类型的其他歌曲
	# song_relevant = Song.objects.filter(song_type=current_song_type).exclude(song_id=current_song.song_id)  # 排除当前歌曲本身


	# print(f'相关歌曲5:{same_type_songs}')	

	song_relevant = Dynamic.objects.select_related('song').filter(song__song_type=song_type).order_by('-dynamic_plays').all()[:6]
	# print(f'相关歌曲6:{song_relevant}')	
	#添加播放次数
	dynamic_info = Dynamic.objects.filter(song_id=int(song_id)).first()
	#判断歌曲动态信息是否存在，存在则在原来基础上+1
	if dynamic_info:
		dynamic_info.dynamic_plays += 1
		dynamic_info.save()
	else:
		dynamic_info = Dynamic(dynamic_plays=1,dynamic_search=0,dynamic_down=0,song_id=song_id)
		dynamic_info.save()

	return render(request,'play.html',locals())




#下载
def download(request,song_id):
	song_info = Song.objects.get(song_id=int(song_id))
	print(f"歌曲信息{song_info}")
	#添加下载次数
	dynamic_info = Dynamic.objects.filter(song_id=int(song_id)).first()
	print(f"歌曲动态信息{dynamic_info}")
	#判断歌曲动态信息是否存在，存在就在原来得基础上+1
	if dynamic_info:
		dynamic_info.dynamic_down += 1
		dynamic_info.save()
	#不存在就创建新得动态信息
	else:
		dynamic_info = Dynamic(dynamic_plays=0,dynamic_search=0,dynamic_down=1,song_id=song_id)
		dynamic_info.save()

	import os
	basedir = os.path.dirname(os.path.abspath(__file__))
		
		#读取文件内容
		# file = 
	file = os.path.join(basedir,'static/songFile/'+song_info.song_file)
		
	# print('文件路径：',file)
	def file_itertor(file,chunk_size=512):
		with open(file,'rb') as f:
			while True:
				c  = f.read(chunk_size)
				if c :
					yield c
				else:
					break
	filename = str(song_id)+'.mp3'

	response = StreamingHttpResponse(file_itertor(file))
	response['Content-type'] = 'application/octet-stream'
	response['Content-Disposition'] = 'attachment;filename="%s"'%(filename)


	return response



	#显示歌曲评论
def comment(request,song_id):
	# form = CommentForm()
	#搜索歌曲
	search_song = Dynamic.objects.select_related('song').order_by('-dynamic_search').all()[:6]
	# print(search_song)
	#提交处理
	if request.method == 'POST':
		
		comment_text = request.POST.get('comment','')
		# print(f'内容呢：{comment_text}')
		comment_user = request.user.username if request.user.username else '匿名用户'
		# print(comment_user)
	
		if comment_text:
			comment = Comment()
			comment.Comment_text = comment_text
			comment.Comment_user = comment_user
			comment.Comment_date = time.strftime('%Y-%m-%d',time.localtime(time.time()))
			comment.song_id = song_id
			try:
				comment.save()
				return redirect(reverse('music:comment', args=[song_id]))
				# return redirect(reverse('music:comment', song_id=song_id))
			except Exception as e:
				print(f'保存评论时出现异常: {e}')  # 打印异常信息

	else:
		song_info = Song.objects.filter(song_id=song_id).first()
		# print(f'这是什么：{song_info}')
		#歌曲不存在抛出404
		if not song_info:
			raise Http404
		
		comment_all = Comment.objects.filter(song_id=song_id).order_by('Comment_date')
		# print(f'这是什么2：{comment_all}')
		song_name = song_info.song_name
		# print(f'这是什么3：{song_name}')

		page = int(request.GET.get('page',1))
		paginator = Paginator(comment_all,2)
		# print(f'这是什么3：{paginator}')
		try:
			contacts = paginator.page(page)
			# print("Contacts paginator:", contacts.paginator)
			# print("Contacts page_range:", contacts.paginator.page_range)

		except PageNotAnInteger:
			print('页面参数不是整数，使用默认第一页')  # 新增的打印语句
			contacts = paginator.page(1)
		except EmptyPage:
			print('页面超出范围，使用最后一页')  # 新增的打印语句
			contacts = Paginator.page(paginator.num_pages)

	return render(request,'comment.html',locals())



def search(request,page):
	if request.method == 'GET':
		search_song = Dynamic.objects.select_related('song').order_by('-dynamic_search').all()[:6]

		kword = request.session.get('kword','')
		if kword:
			song_info =Song.objects.values('song_id','song_name','song_singer','song_time').filter(Q(song_name__icontains=kword)|Q(song_singer__icontains=kword)).order_by('-song_release').all()
		else:
			song_info = Song.objects.values('song_id','song_name','song_singer','song_time').order_by('-song_release').all()[:20]
		
		paginator = Paginator(song_info,2)
		try:
			contacts = paginator.page(page)
		except PageNotAnInteger:
			contacts = paginator.page(1)
		except EmptyPage:
			contacts = paginator.page(paginator.num_pages)
		

		song_exist = Song.objects.filter(song_name=kword)

		dynamic_info = None

		if song_exist:
			song_id = song_exist[0].song_id
			dynamic_info = Dynamic.objects.filter(song_id=int(song_id)).first()
			
			if dynamic_info:
				dynamic_info.dynamic_search += 1
				dynamic_info.save()
			else:
				dynamic = Dynamic(dynamic_plays=0,dynamic_search=1,dynamic_down=0,song_id=song_id)
				dynamic.save()
		
		return render(request,'searc_list.html',locals())
	# else:
	# 	request.session['kword'] = request.POST.get('kword','')
	# 	return redirect(f"music:search?page={page}")
	else:
		# print("接收到的 POST 数据：", request.POST)
		request.session['kword'] = request.POST.get('kword', '')
		# print("准备重定向的 URL：", f"music:search?page={page}")
		return redirect(reverse("music:search", args=[page]))		










# 	#搜索功能
# def search(request):
# 	if request.method == 'POST':
# 		#搜索歌曲

# 		#获取搜索内容，如果关键词为空就提示，并查询全部歌曲
# 		keyword = request.POST.get('keyword','')
# 		# print(f"关键词是：{keyword}")
# 		if not keyword:
# 			song_info = Song.objects.order_by('-song_release').all()[:20]

# 		song_info = Song.objects.filter(Q(song_name__icontains=keyword) | Q(song_singer__icontains=keyword) | Q(song_album__icontains=keyword)).order_by('-song_release').all()
# 		print(f"总数据量: {len(song_info)}")  # 打印总数据量
# 		page = int(request.GET.get('page',1))
# 		# print(f"关当前页面：{song_info}")
# 		paginator = Paginator(song_info,2)

# 		# print(f"总页数: {paginator.num_pages}")  # 打印总页数
# 		try:
# 			contacts = paginator.page(page)
# 			# print(f"当前页数据: {len(contacts)}")  # 打印当前页的数据量
# 			# print(contacts)
# 		except PageNotAnInteger:
# 			print('页面参数不是整数，使用默认第一页')  # 新增的打印语句
# 			contacts = paginator.page(1)
# 		except EmptyPage:
# 			print('页面超出范围，使用最后一页')  # 新增的打印语句
# 			contacts = Paginator.page(paginator.num_pages)

# 		#添加搜索次数
# 		# dynamic_info = None
# 		# song_id = None
# 		song_exist = Song.objects.filter(Q(song_name__icontains=keyword)|Q(song_singer__icontains=keyword))
		
# 		if not song_exist:
# 			print("没搜到1")

# 		song_id = song_exist[0].song_id
# 		dynamic_info = Dynamic.objects.filter(song_id=int(song_id)).first()
			
			
		
# 		#判断歌曲动态信息是否存在
# 		if not dynamic_info:
# 			dynamic = Dynamic(dynamic_plays=0,dynamic_search=1,dynamic_down=0,song_id=song_id)
# 			dynamic.save()

# 		dynamic_info.dynamic_search += 1
# 		dynamic_info.save()

# 	# else:
# 	# 	keyword = request.POST.get('keywords','')
# 	# 	request.session['keywords'] = keyword
# 	# 	return redirect(reverse('music:search', args=[keyword]))
		

# 	return render(request,'searc_list.html',locals())


